<template>
  <section class="contract-file">
    <!-- 头部 -->
    <custom-filter @search="handleSearch" :type="2" from="contractFile" />
    <!-- 表格 -->
    <a-table
      :dataSource="dataList"
      :columns="columns"
      :loading="loading"
      :pagination="pagination"
      @change="handleTableChange"
      rowKey="id"
      :scroll="{ x: 'max-content' }"
      class="mt-10"
      :customRow="customRow"
      sticky
    >
      <template #title>
        <a-row type="flex" justify="space-between" class="table-header">
          <a-col> 合同列表 </a-col>
          <a-col>
            <custom-columns
              :colUrl="colUrl"
              :type="typeList"
              :newIcon="true"
              :resetType="resetType"
              from="contractList"
              @getColumns="getColumns"
            />
          </a-col>
        </a-row>
      </template>

      <template #bodyCell="{ text, record, index, column }">
        <template v-if="column.key === 'owner_name'">
          <a @click.stop="ownerClick(record)">{{ text }}</a>
          <a-tag v-if="record.is_renewal == 1" color="green" class="ml-5"
            >已续</a-tag
          >
        </template>

        <template v-if="column.key === 'lease_endtime'">
          <span>{{ record.lease_endtime }}</span>
          <span v-if="record.timeout_status" style="color: #f9bd99">{{
            record.timeout_data
          }}</span>
          <span v-else style="color: red">{{ record.remind_data }}</span>
        </template>

        <template v-if="column.key === 'contract_tags'">
          <template v-if="text && text.length">
            <tag-list :list="text" :type="2" />
          </template>
          <span v-else>--</span>
        </template>

        <template v-if="column.key === 'settle_status'">
          <a-tag
            color="orange"
            class="ml-5"
            v-if="record.settle_status == '未结清'"
            >{{ record.settle_status }}</a-tag
          >
          <a-tag
            color="green"
            class="ml-5"
            v-else-if="record.settle_status == '已结清'"
            >{{ record.settle_status }}</a-tag
          >
          <span v-else>-</span>
        </template>

        <template v-if="column.key === 'lease_unit_price'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.lease_unit_price_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'lease_deposit'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.lease_deposit_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'is_renewal'">
          <span>{{ text == 1 ? "是" : "否" }}</span>
        </template>

        <template v-if="column.key === 'property_deposit'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.property_deposit_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'property_unit_price'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.property_unit_price_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'lease_real_unit_price'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.lease_real_unit_price_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'property_real_unit_price'">
          <a-space>
            <span>{{ text }}</span>
            <span>{{ record.property_real_unit_price_unit }}</span>
          </a-space>
        </template>

        <template v-if="column.key === 'status'">
          <a-tag :color="$store.getters.contractStatusColor[record.status_key]">
            {{ text }}
          </a-tag>
        </template>

        <template v-if="column.key === 'room_id'">
          <span v-if="record.build_bind && record.build_bind.room.length > 0">
            <a
              v-for="room in record.build_bind.room"
              @click.stop="
                roomClick(
                  room,
                  record.build_bind.room,
                  record.build_bind.village.id
                )
              "
              >{{ room.layer_name + "-" + room.room_name
              }}<text v-if="record.build_bind.room.length > 1">, </text>
            </a>
          </span>
          <span v-else>--</span>
        </template>
      </template>
    </a-table>

    <!-- 房间详情 -->
    <RoomDrawer
      :visible="roomDetailVisible"
      @cancel="cancelRoomDetails"
      :maxRoomNumber="maxRoomNumber"
      :detail="roomDetail"
      pageFrom="SpaceManagement"
    />

    <!-- 租客详情 -->
    <OwnerDetailDrawer
      :visible="ownerDetailVisible"
      :id="ownerId"
      @cancel="ownerDetailVisible = false"
    />

    <!-- 业主详情 -->
    <CreateProprietor
      :visible="proprietorDetailVisible"
      :id="proprietorId"
      drawerType="view"
      @onClose="proprietorDetailVisible = false"
    />
  </section>
</template>

<script>
import {
  defineComponent,
  ref,
  computed,
  watch,
  onActivated,
  reactive,
  toRefs,
} from "vue";
import CustomFilter from "../../../components/contract/CustomFilter/contract.vue";
import { InsertRowAboveOutlined } from "@ant-design/icons-vue";
import request from "../../../common/utils/request";
import store from "../../../store";
import TagList from "../../../components/Tag/show.vue";
import { useRouter } from "vue-router";
const COL_RESET_TYPE = "autoContractListColumn";
import dict from "../../../common/utils/dict";
import CustomColumns from "@/components/CustomColumns/index.vue";
import RoomDrawer from "@/components/village/RoomDrawer.vue";
import OwnerDetailDrawer from "@/views/village/OwnerManage/modules/OwnerDetailDrawer.vue";
import CreateProprietor from "@/views/contract/CostContract/modules/CreateProprietor.vue";

export default defineComponent({
  name: "contractFile",
  components: {
    CreateProprietor,
    OwnerDetailDrawer,
    RoomDrawer,
    CustomColumns,
    CustomFilter,
    TagList,
    InsertRowAboveOutlined,
  },
  setup() {
    const $router = useRouter();
    const state = reactive({
      colUrl: {
        server: "/org",
        url: "/contract/getContractListColumn",
      },
      resetType: COL_RESET_TYPE,
      typeList: dict.CONTRACT_FILE_COL_SET,
      setUrl: {
        server: "/org",
        url: "/user/specialSetting",
      },
    });
    /**
     * @description:  table
     */
    const columns = ref([]);

    const customCols = [
      "owner_name",
      "lease_endtime",
      "contract_tags",
      "settle_status",
      "lease_unit_price",
      "lease_deposit",
      "is_renewal",
      "property_deposit",
      "property_unit_price",
      "lease_real_unit_price",
      "property_real_unit_price",
      "status",
      "room_id",
    ];
    const sorterCols = [
      "owner_name",
      "lease_starttime",
      "lease_endtime",
      "sign_time",
      "room_id",
      "retreat_time",
    ];
    const getColumns = (data) => {
      let arr = [];
      data.forEach((item) => {
        if (item.checked) {
          let col = {
            title: item.title,
            dataIndex: item.key,
            key: item.key,
            width: 150,
          };
          if (sorterCols.includes(item.key)) {
            col.sorter = true;
          }
          arr.push(col);
        }
      });
      columns.value = [...arr];
    };

    // 自定义行
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: (e) => handleTableRowClick(record),
      };
    };
    // 点击行
    const handleTableRowClick = (record) => {
      console.log("handleTableRowClick", record);
      if (window.__MICRO_APP_ENVIRONMENT__) {
        window.microApp.forceDispatch({
          type: "SetMicroPages",
          microInfo: {
            microId: `org_contract_detail`,
            app: 'org',
            name: `合同详情【${record.owner_name}】`,
            url: `/contract/contractDetail?id=${record.id}&noBack=1`,
          }
        })
      }

    };

    const page = ref(1);
    const limit = ref(10);
    const total = ref(0);
    const pagination = computed(() => ({
      total: total.value,
      current: page.value,
      pageSize: limit.value,
      showSizeChanger: true,
    }));
    const loading = ref(false);
    const sort = ref("");
    const order = ref("");
    const handleTableChange = (pager, filters, sorter) => {
      if (sorter) {
        if (sorter.order) {
          sort.value = sorter.order == "ascend" ? "asc" : "desc";
          order.value = sorter.field;
        } else {
          order.value = "";
          sort.value = "";
        }
      }
      page.value = pager.current;
      limit.value = pager.pageSize;
    };

    watch([page, limit, sort, order], () => {
      getTableData();
    });
    const dataList = ref([]);
    const getTableData = () => {
      loading.value = false;
      request
        .post("/org", "/contract/contractFile", {
          page: page.value,
          limit: limit.value,
          sort: sort.value,
          order: order.value,
          ...searchValue.value,
        })
        .then((res) => {
          dataList.value = res.list;
          total.value = res.total;
        })
        .finally(() => {
          loading.value = false;
        });
    };

    const searchValue = ref({});
    const handleSearch = (params) => {
      searchValue.value = params;
      getTableData();
    };

    const init = () => {
      getTableData();
    };

    onActivated(() => {
      init();
    });

    // 获取最大房源号
    const getMaxRoomNumber = (list) => {
      let max = 0;
      for (let room of list) {
        if (max < Number(room.room_number)) {
          max = Number(room.room_number);
        }
      }
      return max;
    };

    // 房间点击详情
    const maxRoomNumber = ref(0);
    const roomDetailVisible = ref(false);
    const roomDetail = ref({});
    const roomClick = (room, room_list, village_id) => {
      // console.log(room, layer);
      let roomData = room;
      roomData.village_id = village_id;
      roomDetail.value = roomData;
      maxRoomNumber.value = getMaxRoomNumber(room_list);
      roomDetailVisible.value = true;
    };
    const cancelRoomDetails = () => {
      roomDetailVisible.value = false;
    };

    // 租客详情
    const ownerDetailVisible = ref(false);
    const ownerId = ref(0);

    // 业主详情
    const proprietorDetailVisible = ref(false);
    const proprietorId = ref(0);

    const ownerClick = (record) => {
      if (record.owner_id) {
        ownerId.value = record.owner_id;
        ownerDetailVisible.value = true;
      } else if (record.proprietor_id) {
        if (record.is_new == 1) {
          ownerId.value = record.proprietor_id;
          ownerDetailVisible.value = true;
        } else {
          proprietorId.value = record.proprietor_id;
          proprietorDetailVisible.value = true;
        }
      }
    };

    return {
      ...toRefs(state),
      columns,
      dataList,
      pagination,
      loading,
      handleTableChange,
      handleSearch,
      customRow,
      getColumns,
      roomDetailVisible,
      maxRoomNumber,
      roomDetail,
      roomClick,
      cancelRoomDetails,
      ownerDetailVisible,
      ownerId,
      ownerClick,
      proprietorDetailVisible,
      proprietorId,
    };
  },
});
</script>

<style lang="less" scoped>
.contract-file {
  padding: 10px;
  .table-header {
    margin: 0 20px;
    color: rgba(0, 0, 0, 0.8);
  }
}
</style>
